<?php
namespace common\core\config;

use Yii;
use yii\base\Model;

class ConfigForm extends Model
{
    public function initAllConfigItem()
    {
        $this->initAllInternal();
    }
    
	public function saveAllConfigItem()
	{
		$this->saveAllInternal();
	}

	protected function getAllKeys()
	{
		return array_keys($this->attributeLabels());
	}
	
	protected function initAllInternal()
	{
	    $keys = $this->getAllKeys();
	    foreach($keys as $key)
	    {
	        $this->initOne($key, $this->$key);
	    }
	}
	
	protected function initOne($key, $defaultValue)
	{
	    /**
	     * var common\modules\storage\StorageService $storageService
	     */
	    $storageService = getStorageService();
	    $model = $storageService->loadConfig($key);
		if($model != null)
		{
			$this->$key = $model->value;
		}
		else
		{
		    if(empty($defaultValue) && $this->$key!==null)
		    {
		        $defaultValue = $this->$key;
		    }
		    $storageService->saveConfig($key, $defaultValue);
			
			$this->$key = $defaultValue;
		}
	}

	protected function saveAllInternal()
	{     
	    $keys = $this->getAllKeys();
		foreach($keys as $key)
		{
			$this->saveOne($key, $this->$key);
		}
	}

	protected function saveOne($key, $value)
	{
	    /**
	     * var common\modules\storage\StorageService $storageService
	     */
	    $storageService = getStorageService();
	    $storageService->saveConfig($key, $value);
	}
}
